package com.labbit.platform.commons.session;

import com.labbit.platform.commons.properties.CommonProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis session 存储
 * @author ChenYu
 * @date 2017/12/14 16:53
 */
@Component("redisSession")
public class RedisSession<E> implements ISession<E> {

    @Autowired
    private CommonProperties commonProperties;

    //session前缀
    private static final String sessionPrefix = "session_";

    @Autowired
    private RedisTemplate<String, E> redisTemplate;

    @Override
    public E get(String key) {
        //更新过期时间
        String newKey = sessionPrefix + key;
        redisTemplate.opsForValue().getOperations().expire(newKey, commonProperties.getSessionTimeout(), TimeUnit.SECONDS);
        return redisTemplate.opsForValue().get(newKey);
    }

    @Override
    public void put(String key, E session) {
        redisTemplate.opsForValue().set(sessionPrefix + key, session, commonProperties.getSessionTimeout(), TimeUnit.SECONDS);
    }

    @Override
    public void remove(String key) {
        redisTemplate.opsForValue().getOperations().delete(sessionPrefix + key);
    }

    @Override
    public void removeAll() {

    }
}
